Repository navigation
feat(pm-stack): decision-set event pipeline — Turso sync + Cloudflare Worker/D1/DO (#9335) - #9341
Conversation
… Worker/D1/DO (#9335) Track B of Decision Sets v2. Aggregator: src/decision-events.ts (wire shape {eventId,setId,questionRef,type,payload,ts}, JSONL outbox reader, libSQL pipeline client, per-leg sync state) + scripts/sync-decision-events.ts (strict #3352 arg contract; tokens by BWS name turso.fleet-platform-rw-token / cloudflare.decision-events.webhook-secret; INSERT OR IGNORE idempotent on eventId; legs fail independently). Worker: pm-stack/decision-events-worker — POST /events authenticated webhook -> D1 (decision-events DB) + Durable Object per setId (fan-out state + WebSocket stream), GET read-backs, fail-closed auth. Deployed and smoke-verified live; see issue #9335 outcome comment.
|
Warning Review limit reachedYou've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository. Next included review available in 44 minutes. View limit details
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. |
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 81461b36d3
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| const changes = r.meta?.changes ?? 0; | ||
| inserted += changes; | ||
| if (changes > 0) insertedEvents.push(events[i] as DecisionSetEvent); | ||
| }); | ||
|
|
||
| const fanout: Record<string, unknown> = {}; | ||
| for (const [setId, setEvents] of groupBySet(insertedEvents)) { |
There was a problem hiding this comment.
Preserve pending fan-out across D1 deduplication
If the Durable Object ingest fails after the D1 batch commits, these events can never reach the object on retry: their next inserts report zero changes, so insertedEvents excludes them permanently. A non-OK ingest response is also converted into an HTTP 200 webhook response, causing the sync client to acknowledge the events despite the failed fan-out. Persist pending fan-out separately and retry it, with event-ID deduplication at the Durable Object, so transient failures do not permanently lose subscriber notifications and coordination state.
Useful? React with 👍 / 👎.
| const out = (await res.json().catch(() => null)) as { inserted?: unknown } | null; | ||
| if (!out || typeof out.inserted !== "number") throw new Error("webhook failed: malformed response"); | ||
| inserted += out.inserted; |
There was a problem hiding this comment.
Check webhook acceptance before acknowledging the batch
The Worker returns HTTP 200 even when individual events fail validation, but this client checks only inserted and then syncDecisionEvents marks every pending event acknowledged. This occurs with the current implementations: an outbox event with ts: "2026-11-12" passes the aggregator's isIsoDate validation but is rejected by the Worker's timestamp validator, which requires T. The event is consequently never stored in D1 and never retried. Check the response's acceptance count and per-event errors before advancing acknowledgment state, and align the two validators.
Useful? React with 👍 / 👎.
| const after = url.searchParams.get("after"); | ||
| const query = after | ||
| ? "SELECT event_id, set_id, question_ref, type, payload, ts FROM decision_set_events WHERE set_id = ? AND ts > ? ORDER BY ts, event_id LIMIT ?" | ||
| : "SELECT event_id, set_id, question_ref, type, payload, ts FROM decision_set_events WHERE set_id = ? ORDER BY ts, event_id LIMIT ?"; |
There was a problem hiding this comment.
Include the event ID in the read-back pagination cursor
When a page ends within a group of events sharing the same timestamp, requesting the next page with after equal to the last returned timestamp skips all remaining events in that group. For example, three events with identical ts values and limit=2 make the third event unreachable through pagination. The ordering already uses (ts, event_id); expose and apply that same composite cursor so bounded read-back does not omit events.
Useful? React with 👍 / 👎.
| if (process.env.DECISION_EVENTS_SYNC === "0") { | ||
| console.log("sync-decision-events: disabled by DECISION_EVENTS_SYNC=0"); | ||
| return 0; | ||
| } | ||
| const opts = parseArgs(); |
There was a problem hiding this comment.
Parse arguments before returning for the kill switch
With DECISION_EVENTS_SYNC=0, the script returns success before validating arguments, so an invocation such as --targte webhook silently succeeds instead of reporting a usage error. This violates the operator-script contract in AGENTS.md, which requires every unaccounted-for argument to produce a non-zero usage error. Move parseArgs() ahead of the kill-switch return so disabled invocations still validate their command line.
AGENTS.md reference: AGENTS.md:L47-L50
Useful? React with 👍 / 👎.
| const opts = parseArgs(); | ||
| const files = opts.files.length > 0 ? [...opts.files] : [defaultDecisionEventsOutboxFile()]; | ||
| if (opts.outboxDir) { | ||
| const entries = await readdir(opts.outboxDir).catch(() => [] as string[]); |
There was a problem hiding this comment.
Report failures to read the explicitly requested outbox directory
If the directory supplied through --outbox-dir is unreadable, missing, or actually a regular file, this catch converts the read failure into an empty directory without any diagnostic. The script then continues with the default outbox and can exit successfully with zero pending events while leaving the requested source completely unsynchronized. Propagate directory-read failures or report them and return a non-zero exit status so operators can distinguish a broken source from an empty outbox.
Useful? React with 👍 / 👎.
…trackb # Conflicts: # pm-stack/aggregator/src/decision-events.ts
What
Track B of Decision Sets v2 (#9335): the external event pipeline for decision-set activity events
{eventId, setId, questionRef, type, payload, ts}.Aggregator side (
pm-stack/aggregator)src/decision-events.ts— the wire contract + outbox reader (JSONL, default~/.local/state/pm-aggregator/decision-events-outbox.jsonl), a libSQL HTTP pipeline client (typed args, malformed-envelope-safe, per the design: move agent append streams (agent.events, agent.quota_records) from Supabase to Turso staging #5690/github-ci(turso client): a wrong-shape 200 response is read as success or escapes as a raw TypeError — batch() never validates the pipeline envelope #6949 pattern), and per-leg sync state (acked eventIds per sink; corrupt state re-syncs, sinks dedupe).scripts/sync-decision-events.ts— operator sync script (strict Design: unknown means stop — one strict argument contract for the repo's operator scripts #3352 argument contract). Two independent legs, bothINSERT OR IGNOREoneventId:decision_set_events, token by BWS nameturso.fleet-platform-rw-token(the gather-quota.ts precedent from design: move agent append streams (agent.events, agent.quota_records) from Supabase to Turso staging #5690).cloudflare.decision-events.webhook-secret.test/decision-events.test.ts— 11 tests (validation, outbox parsing/dedupe, fake-libSQL oracle proving insert-once idempotence, leg independence, state round-trip).Worker (
pm-stack/decision-events-worker)POST /events(alias/webhook): constant-time shared-secret auth, batch validation (one bad event never poisons a batch), D1 store, then per-set Durable Object fan-out of only the newly inserted events.DecisionSetEventsDurable Object, keyed byidFromName(setId): per-set fan-out state (count, last event) + hibernatable WebSocket subscribers (GET /sets/<id>/stream).GET /sets/<id>/events,GET /sets/<id>/stateread-backs (authenticated);GET /healthpublic; fails closed (503) with no secret configured.test/events.test.ts— 7 contract tests;tsc --noEmitclean.Live state (already deployed — this PR is the source of record)
decision_set_events+ indexes created in fleet-platform; verified by independent pipeline read-back.decision-events(68ade85e-6835-46a8-af6a-a9f2f2d966ae) created,schema.sqlapplied remotely.9e5607c8-b26d-47d3-b671-d1465e114253),WEBHOOK_SECRETset from the BWS-vaulted value by name.cloudflare.decision-events.webhook-secret; value never in repo/logs.smoke-9335→ Turso inserted=1×3, Worker inserted=1×3; re-run with fresh state → attempted=3, inserted=0 on both legs (sink-level idempotence); Worker/stateshows the DO at fannedOut=3, D1=3; unauthenticated GET/POST → 401.Verification
bun test test/decision-events.test.ts11/11; neighboringdecisions+eventssuites still green (79/79 across the three files). Typecheck: 20 errors = exact origin/main baseline, 0 in new files.bun test7/7,tsc --noEmitclean.affected_row_count(notrows_affected) — the counter and the test fake now match the real envelope.Not in this PR
Track A's local event-log producer (the aggregator-side appends to the outbox) is the parallel leg; this sync consumes whatever JSONL outbox carries the wire shape (
--file/--outbox-diroverridable). No timer/cron wiring yet — the sync is safe to run on any cadence once Track A's outbox path is final.Refs #9335
Open in [code]smith · Need help on this PR? Tag
@codesmith-botwith what you need.